﻿using CqCore.Commands;
using CqCore.Logging;
using Newtonsoft.Json.Linq;
using SuperShopInfrastructure.Extensions;
using SuperShopInfrastructure.Models.User;
using SuperShopInfrastructure.Static;
using SuperShopInfrastructure.Weixin.Services;
using SuperShopRepository;
using SuperShopService.IServices;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace SuperShopService.Services
{
    public class UserService : IUserService
    {
        private readonly UserRepository userRepository;
        private readonly ILogRecorder<ProductService> logRecorder;
        private readonly IShopAppService shopAppService;
        private readonly WeiXinHelper weiXinHelper;

        public UserService(
            UserRepository userRepository,
            ILogRecorder<ProductService> logRecorder,
            IShopAppService shopAppService,
            WeiXinHelper weiXinHelper)
        {
            this.userRepository = userRepository;
            this.logRecorder = logRecorder;
            this.shopAppService = shopAppService;
            this.weiXinHelper = weiXinHelper;
        }

        public async Task<CommandResult<WxUserLoginViewModel>> WxUserLoginOrRegister(WxUserLoginCommand command)
        {
            var shopAppModel = await shopAppService.GetShopAppModel(command.Spid.ToInt());
            if (shopAppModel == null)
                return CommandResult<WxUserLoginViewModel>.Failure("获取店铺模型出错");
            string authorJson = weiXinHelper.GetOpenIdStr(shopAppModel.AppId, shopAppModel.AppSecret, command.Code);

            JObject jo = JObject.Parse(authorJson);
            string openid = jo["openid"].ToString();
            command.OpenId = openid;

            var res = new WxUserLoginViewModel();
            var ds = await userRepository.WxUserLoginOrRegister(command);
            if (DataManager.CheckDs(ds, 1) && DataManager.CheckHasRow(ds.Tables[0]))
            {
                DataRow dr = ds.Tables[0].Rows[0];
                res.Id = SecretClass.EncryptQueryString(dr["Id"].ToString());
                res.NickName = dr["NickName"].ToString();
                res.HeadImgUrl = dr["HeadImgUrl"].ToString();
                res.Token = dr["Token"].ToString();
                res.ShopName = dr["ShopName"].ToString();
                res.OptionStatus = DataManager.GetRowValue_Int(dr["OptionStatus"]);
                res.CreateTime = DataManager.GetRowValue_DateTime(dr["CreateTime"]);
            }
            if (string.IsNullOrEmpty(res.Token))
                return CommandResult<WxUserLoginViewModel>.Failure("用户请求异常");
            res.ShopName = shopAppModel.ShopName;
            return CommandResult<WxUserLoginViewModel>.Success(res);
        }
    }
}
